/**
*  \file can_open.h
*
*  \brief
*
*  \authors Dajin Li  dajin.li@linde-.de
*
*
*
*/


#ifndef CAN_OPEN_H
#define CAN_OPEN_H


/*================================================[ public includes  ]================================================*/



#include "var/var_tbl.h"
#include "../xmc4500/can_drv.h"
/*================================================[ public defines   ]================================================*/
// For all the truck   

#define BootSWAddress                           0x08000000
#define ApplicationSWAddress                    0x08080000
#define BootBISAddress                          0x0800FFE0
#define AppBISAddress                           0x080FFFE0
#define AppEndAddress                           0x08100000
#define AppLength                               0x80000

#define VAR_LENGTH_MASK                         0x00FF
#define READ_WRITE                              0x8000
#define LIMIT_CHK                               0x4000
#define SIGNED_VAR                              0x2000
#define STR_VAR                                 0x1000
#define SAVE_TO_EE                              0x0800





#define NMT                         0x0     // Network Management
#define SYNC_ERR                    0x1     // Both Sync (COB-ID=0) & Error (COB-ID=Error)
#define RESV_1                      0x2
#define PDO_MISO                    0x3     // Process Data Object (Master In  Slave Out)
#define PDO_MOSI                    0x4     // Process Data Object (Master Out Slave In)
#define PDO_SYS1                    0x5     // Process Data Object (System Broadcast 1)
#define PDO_SYS2                    0x6     // Process Data Object (System Broadcast 2)
#define PDO_SYS3                    0x7     // Process Data Object (System Broadcast 3)
#define PDO_SYS4                    0x8     // Process Data Object (System Broadcast 4)
#define IDO_MISO                    0x9     // Index Data Object (Master In  Slave Out)
#define IDO_MOSI                    0xA     // Index Data Object (Master Out Slave In)
#define SDO_MISO                    0xB     // Service Data Object (Master In  Slave Out)
#define SDO_MOSI                    0xC     // Service Data Object (Master Out Slave In)
#define RESV_2                      0xD
#define NODE                        0xE     // Node Guard Message
#define RESV_3                      0xF


// For all the truck                 
#define TRAC_KWP_RX_ID_ALL                              0x780   // KWP RX Id

#define TRAC_KWP_RX_ID                                  0x781   // KWP RX Id
#define TRAC_KWP_TX_ID                                  0x791   // KWP TX Id

#define TRAC_KWP_INIT01_RX_ID_ALL                       0x3E1   // KWP init01 rx id
#define TRAC_KWP_INIT01_TX_ID_ALL                       0x3F1   // KWP init01 tx id
                                                        
#define KWP_SINGLE_FRM                                  0x00    // single frame
#define KWP_FIRST_FRM                                   0x01    // first frame-segmented transfer
#define CONSECUTIVE_FRM                                 0x02    // flow control frame
#define KWP_FLOW_CONTROL_FRM                            0x03    // flow control frame
#define CONTINUE_TO_SEND                                0x00    // continue to send
#define KWP_FUN_NOT_SUPPORT                             0x12
#define KWP_SERVICE_NOT_SUPPORT                         0x11
#define KWP_GENERAL_REJECT                              0x10
#define KWP_BUSY                                        0x21
#define KWP_SEQUECNCE_ERROR                             0x22
#define KWP_SERVICE_IN_PROGRESS                         0x23
#define KWP_OUTOF_RAGNGE                                0x31
#define KWP_SECURITY_DENIED                             0x33
#define KWP_INVALID_KEY                                 0x35
#define KWP_EXCEED_ATTEMPTS                             0x36
#define KWP_NOT_EXPIRED                                 0x37
#define KWP_DOWNLOAD_NOT_ALLOW                          0x40
#define KWP_DOWNLOAD_TYPE_ERROR                         0x41
#define KWP_DOWNLOAD_ADDR_ERROR                         0x42
#define KWP_DOWNLOAD_BYTES_ERROR                        0x43
#define KWP_UPLOAD_NOT_ALLOW                            0x51
#define KWP_UPLOAD_ADDR_ERROR                           0x52
#define KWP_UPLOAD_BYTES_ERROR                          0x53

// * These are the state definitions reported in can_nmt_state
#define SHIFT_5_BITS                                    5
#define CAN_OPEN_ENABLED                                0x0100
#define RD_ECU_OK                                       0x5A
#define KWP_FAIL                                        0x7F
#define KWP_RD_DATA_OK                                  0x61
#define KWP_WR_DATA_OK                                  0x7B
#define KWP_SECURITY_OK                                 0x67
#define KWP_START_FLASH                                 0x01   
#define KWP_DEL_FLASH                                   0x02  
#define KWP_CAL_CHECKSUM                                0x03  
#define KWP_PASSIVE_MODE                                0x04    
#define KWP_INIT01                                      0x80                                                        
#define KWP_EMERGENCY_FLASH                             0xFB                                                        
#define KWP_DEFAULT_SESSION                             0x81
#define KWP_START_PROGRAMING_SESSION                    0x85
#define KWP_START_DEFAULT_SESSION_OK                    0x50
#define FOUR_BYTES_LEN                                  4
#define TWO_BYTES_LEN                                   2
#define ONE_BYTES_LEN                                   1
#define FILTER_MASK                                     0x7FF    // 111 1001 1111 // message type 1111 00 master id 11111 slave id 
#define BLK_INDEX_MASK                                  0x0F
#define BUFFER_SIZE                                     4096

#define STD_MASK                                        0xFFE0 // 1111 1111 1110 // message type 1111 11 master id 11111 slave id 



/** Security Access 1/2 supported */
#define SECACC_12                                       1

/** Security Access 3/4 supported */
#define SECACC_34                                       1

/** Security Access 5/6 supported */
#define SECACC_56                                       0
#define KWP_CHKBUF_LEN                                  256 

 #define fls_PLACE_IN_RAM __attribute__ ((optimize(3), section(".ram_code")))


/*================================================[ public datatypes ]================================================*/

/* Message ID types*/
enum
{
    CAN_STD_ID,
    CAN_EXT_ID
};

struct CAN_SYSTEM_BITS
{
    int CAN_Enabled:1;
    int PDO_Timed_Out:1;
    int Write_EE_CAN:1;
    int CAN_PDO_Timeouts_On:1;
    int CAN_PDO_Enabled:1;
    int CAN_SDO_Enabled:1;
    int CAN_SDO_Block_Download:1;
    int CAN_SDO_Block_DISConnect:1;
    int CAN_Message_Center_Unpdate:1;
};
/** Security States */
enum secacc_state
{
   secacc_state_default       =  0x00,  /**< No security level          */
   secacc_state_programming   =  0x01,  /**< Programming State          */
   secacc_state_service       =  0x03,  /**< Field Flash                */
   secacc_state_eopl          =  0x05   /**< End Of Production Line     */
};

/** Standard KWP2000 error codes */
enum kwp_response_code
{
   KWP_RESPONSE_CODE_GENERALREJECT                    = 0x10,
   KWP_RESPONSE_CODE_SERVICENOTSUPPORTED              = 0x11,
   KWP_RESPONSE_CODE_SUBFUNCTIONNOTSUPPORTED          = 0x12,
   KWP_RESPONSE_CODE_INVALIDFORMAT                    = 0x12,
   KWP_RESPONSE_CODE_BUSYREPEATREQUEST                = 0x21,
   KWP_RESPONSE_CODE_CONDITIONSNOTCORRECT             = 0x22,
   KWP_RESPONSE_CODE_REQUESTSEQUENCEERROR             = 0x22,
   KWP_RESPONSE_CODE_ROUTINENOTCOMPLETED              = 0x23,
   KWP_RESPONSE_CODE_REQUESTOUTOFRANGE                = 0x31,
   KWP_RESPONSE_CODE_RESPONSEPENDING                  = 0x78,
   KWP_RESPONSE_CODE_SERVICENOTSUPPORTEDINACTIVEMODE  = 0x80,
   KWP_RESPONSE_CODE_ACCESSDENIED                     = 0x33,
   KWP_RESPONSE_CODE_INVALIDKEY                       = 0x35,
   KWP_RESPONSE_CODE_EXCEEDNUMOFATTEMPTS              = 0x36,
   KWP_RESPONSE_CODE_TIMEDELAYNOTEXPIRED              = 0x37,
   KWP_RESPONSE_CODE_DOWNLOADNOTACCEPTED              = 0x40,
   KWP_RESPONSE_CODE_IMPROPERDOWNLOADTYPE             = 0x41,
   KWP_RESPONSE_CODE_CANNTDOWNLOADTOADDRESS           = 0x42,
   KWP_RESPONSE_CODE_CANNTDOWNLOADNUMOFBYTES          = 0x43,
   KWP_RESPONSE_CODE_UPLOADNOTACCEPTED                = 0x50,
   KWP_RESPONSE_CODE_IMPROPERUPLOADTYPE               = 0x51,
   KWP_RESPONSE_CODE_CANNTUPLOADFROMADDRESS           = 0x52,
   KWP_RESPONSE_CODE_CANNTUPLOADNUMOFBYTES            = 0x53,
   KWP_RESPONSE_CODE_TRANSFERSUSPENDED                = 0x71,
   KWP_RESPONSE_CODE_TRANSFERABORTED                  = 0x72,
   KWP_RESPONSE_CODE_ILLEGALADDRESSINBLOCKTRANSFER    = 0x74,
   KWP_RESPONSE_CODE_ILLEGALBYTECOUNTINBLOCKTRANSFER  = 0x75,
   KWP_RESPONSE_CODE_ILLEGALBLOCKTRANSFERTYPE         = 0x76,
   KWP_RESPONSE_CODE_BLOCKTRANSFERDATACHECKSUMERROR   = 0x77,
   KWP_RESPONSE_CODE_INCORRECTBYTECNTDGBLOCKTRANSFER  = 0x79,
   KWP_RESPONSE_CODE_INVALIDCHECKSUM                  = 0xFB,
   KWP_RESPONSE_CODE_NONE                             = 0x00
};


enum kwpdiag_sid
{
    startDiagnosticSession              = 0x10,
    ecuReset                            = 0x11,
    readDiagnosticTroubleCodes          = 0x13,
    clearDiagnosticInformation          = 0x14,
    readStatusOfDiagnosticTroubleCodes  = 0x17,
    readDiagnosticTroubleCodesByStatus  = 0x18,
    readECUIdentification               = 0x1A,
    stopDiagnosticSession               = 0x20,
    readDataByLocalIdentifier           = 0x21,
    readMemoryByAddress                 = 0x23,
    securityAccess                      = 0x27,
    inputOutputControlByLocalIdentifier = 0x30,
    startRoutineByLocalIdentifier       = 0x31,
    requestDownload                     = 0x34,
    transferData                        = 0x36,
    requestTransferExit                 = 0x37,
    writeDataByLocalIdentifier          = 0x3B,
    writeMemoryByAddress                = 0x3D,
    testerPresent                       = 0x3E
};


enum kwptp_state
{
    kwptp_state_idle,
    kwptp_state_flow_control,
    kwptp_state_sendig,
    kwptp_state_waiting_for_flow_ctrl,
    kwptp_state_rx_completed,
    kwptp_state_aborted,
    kwptp_state_timeout
};

union CAN_SYSTEM_FLAGS
{
    s16                     all;
    struct CAN_SYSTEM_BITS  bit;
};
#define CAN_Enabled                     CanSystemFlags.bit.CAN_Enabled
#define PDO_Timed_Out                   CanSystemFlags.bit.PDO_Timed_Out
#define Write_EE_CAN                    CanSystemFlags.bit.Write_EE_CAN
#define CAN_PDO_Timeouts_On             CanSystemFlags.bit.CAN_PDO_Timeouts_On
#define CAN_PDO_Enabled                 CanSystemFlags.bit.CAN_PDO_Enabled
#define CAN_SDO_Enabled                 CanSystemFlags.bit.CAN_SDO_Enabled
#define CAN_SDO_Blk_Download            CanSystemFlags.bit.CAN_SDO_Block_Download
#define CAN_SDO_Blk_DISConnect          CanSystemFlags.bit.CAN_SDO_Block_DISConnect

/** Fortune object */
struct fortune
{
   u32 random;
};



/*================================================[ public variables ]================================================*/
extern union CAN_SYSTEM_FLAGS CanSystemFlags;
extern u32 startAddr;
extern u32 endAddr;
extern u32 flash_length;
extern u8 sdo_data[8];
extern u8 Can_Rx_buf[BUFFER_SIZE];

/*================================================[ inline functions ]================================================*/

/*================================================[ public functions ]================================================*/
extern s16 canopen_init(void);
extern void process_msg(can_mailbox *message);
extern void Multi_msg_send(void);
void KWP_send_boot_msg(void);

extern void KWP_send_pending_msg(void);

#endif // CAN_OPEN_H 

/***********************************************************************************************************************
*                             Copyright 2016 Linde Material Handling. All rights reserved.                             *
***********************************************************************************************************************/


